<script lang="ts" setup>
  import { getDeptTreeList } from '@/api/departmentManagement'
  import { ElCascader } from 'element-plus'
  const props = defineProps({
    ...ElCascader.props,
    modelValue: {
      type: String,
      default: '',
    },
    immediateLoad: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
  })
  const emits = defineEmits('update:modelValue')
  const departmentVal = ref([])
  const department = reactive({
    list: [],
  })
  let defaultProps = reactive({
    expandTrigger: 'hover',
    label: 'label',
    value: 'value',
  })

  const getDepartmentList = async () => {
    const { data } = await getDeptTreeList()
    department.list = data || []
  }

  const handleDepartmentChange = (val) => {
    emits('update:modelValue', val)
  }

  onMounted(() => {
    if (Object.keys(props.props).length > 0) {
      defaultProps = Object.assign({}, defaultProps, props.props)
    }
    if (props.immediateLoad) {
      defaultProps.filterable = true
      getDepartmentList()
    }
    if (props.data && props.data.length > 0) {
      department.list = props.data || []
    }
  })
</script>

<template>
  <el-cascader
    v-model="departmentVal"
    v-bind="props"
    :options="department.list"
    :props="defaultProps"
    @change="handleDepartmentChange"
  />
</template>
